package com.handong.handdemo.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.provider.Settings;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.offlinemap.OfflineMapManager;
import com.handong.handdemo.R;
import com.handong.handdemo.util.ByteUtils;
import com.handong.handdemo.util.DialogUtils;
import com.handong.handdemo.util.help.GetAplicationData;
import com.zps.ylibrary.YModem;
import com.zps.ylibrary.YModemListener;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;

import cn.pda.serialport.SerialPort;
import cn.pda.serialport.Tools;

import static android.icu.lang.UCharacter.GraphemeClusterBreak.L;

public class UpdateActivity extends AppCompatActivity {
    private String TAG = "YMODEM";
    private TextView mTvresult, mTvProgress;
    private EditText mEt_file;
    private File mFirmwareFile;
    private ProgressBar mPBProgressBar;
    private Button mBtnstatdownload,map;


    private SerialPort mSerialPort;   //串口工具类
    private InputStream mReadStream;
    private OutputStream mWriteStream;
    private String path;

    private Context context;
    private Boolean canGet=false;
    private OfflineMapManager  mOfflineMapManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update);
        context=UpdateActivity.this;
        initUI();
        initDate();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                    doWork();

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void doWork() {
        Log.d(TAG,"开始处理。。。。");
        mSerialPort.rfid_poweron();
        try {
            mSerialPort.openSerial(13, 115200);
        } catch (IOException e) {
            e.printStackTrace();
            Log.d(TAG, e.toString());
        }
        if ((this.mReadStream == null) || (this.mWriteStream == null)) {
            Log.d(TAG, "byte:" + null);

            this.mReadStream = this.mSerialPort.getInputStream();
            this.mWriteStream = this.mSerialPort.getOutputStream();
        }
        while (true) {
            try {
                if (mReadStream.available() > 0) {
                    byte[] buff = new byte[mReadStream.available()];//获取全部数据
                    if ((mReadStream.read(buff)) != 0 && buff.length <6 ) {
                        Log.d(TAG, "收到数据2：" + Arrays.toString(buff));
                        if (canGet){
                            ymodem.onReceiveData(buff);
                        }

                    }
                }
            }catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private void initUI() {
        mEt_file = findViewById(R.id.et_file_show);
        mTvresult = findViewById(R.id.tv_result);
        mTvProgress = findViewById(R.id.tv_progress);
        mPBProgressBar = findViewById(R.id.pb_progress);
        mBtnstatdownload = findViewById(R.id.btn_stat_download);
        map = findViewById(R.id.map);

    }

    private void initDate() {
        updateTitle();
        updateMapMes();
//        requestPermission();
        mSerialPort = new SerialPort();

        //搜索文件按钮点击召唤文件选择dialog
        findViewById(R.id.btn_file_select).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtils.select_file(UpdateActivity.this, new DialogUtils.DialogSelection() {
                    @Override
                    public void onSelectedFilePaths(String[] files) {
                        if (files.length == 1) {
                            mEt_file.setText(files[0]);
                            path=files[0];
                            mFirmwareFile = new File(files[0]);
                        }
                    }
                });
            }
        });
        mTvresult.setMovementMethod(ScrollingMovementMethod.getInstance());

        //开始文件传输
        mBtnstatdownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mTvresult.setText("");
                mPBProgressBar.setVisibility(View.VISIBLE);
                if (mFirmwareFile != null && mFirmwareFile.exists()) {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            if (mSerialPort != null) {
                                startTransmission();
                            }
                        }
                    }).start();
                } else {
                    showToast("选择一个合法的bin文件");
                }

            }
        });
        map.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String ss=GetAplicationData.sHA1(UpdateActivity.this);
                Log.d(TAG,"sha1:"+ss);
                startActivity(new Intent(UpdateActivity.this,
                        com.amap.api.maps.offlinemap.OfflineMapActivity.class));
            }
        });
    }

    private void updateMapMes() {
        MapsInitializer.updatePrivacyShow(context,true,true);
        MapsInitializer.updatePrivacyAgree(context,true);
    }

    public void showToast(String str) {
        Toast.makeText(UpdateActivity.this, str, Toast.LENGTH_SHORT).show();
    }
    private void beginFileInput(byte[] data) {
        if ((this.mReadStream == null) || (this.mWriteStream == null)) {
            Log.d(TAG,"流为空");
            this.mReadStream = this.mSerialPort.getInputStream();
            this.mWriteStream = this.mSerialPort.getOutputStream();
        }
        try {
            this.mWriteStream.write(data);
            Log.e(TAG, "写入数据长度："+data.length);
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "循环发送命令" + Tools.byteToHexString(data) + "。");
        }
    }



    //更新标题和权限申请
    private void updateTitle() {
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            setTitle(getString(R.string.app_name) + "固件升级  V " + packageInfo.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
        }
    }
    private YModem ymodem;
    private void startTransmission() {
        Looper.prepare();
        Log.d(TAG,"开始传输=====");
        ymodem = new YModem.Builder()
                .with(this)
                .filePath("file://"+path)
                .fileName(mFirmwareFile.getName())
                .callback(new YModemListener() {
                    @Override
                    public void onDataReady(byte[] data) {
                        Log.d(TAG,"onDataReady :"+ Arrays.toString(data));
                        beginFileInput(data);
                    }

                    @Override
                    public void onProgress(int currentSent, int total) {
                        Log.d(TAG,"onProgress 。。。。"+"currentSent:"+currentSent +"total:"+total);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mTvProgress.setText(currentSent/total*100+"%");
                                mPBProgressBar.setProgress(currentSent/total);
                            }
                        });
                        //the progress of the file data has transmitted

                    }

                    @Override
                    public void onSuccess() {
                        //we are well done with md5 checked
                        Toast.makeText(UpdateActivity.this,"成功",Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onFailed(String reason) {
                        Toast.makeText(UpdateActivity.this,"失败",Toast.LENGTH_SHORT).show();
                    }
                }).build();

        ymodem.start();
        canGet=true;
        Looper.loop();
    }



    //申请权限
    private static final String[] VIDEO_PERMISSIONS = {Manifest.permission.CAMERA,Manifest.permission.RECORD_AUDIO,Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static final int VIDEO_PERMISSIONS_CODE = 1;
    private void requestPermission() {
        // 当API大于 23 时，才动态申请权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ActivityCompat.requestPermissions(UpdateActivity.this,VIDEO_PERMISSIONS,VIDEO_PERMISSIONS_CODE);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case VIDEO_PERMISSIONS_CODE:
                //权限请求失败
                if (grantResults.length == VIDEO_PERMISSIONS.length) {
                    for (int result : grantResults) {
                        if (result != PackageManager.PERMISSION_GRANTED) {
                            //弹出对话框引导用户去设置
                            showDialog();
                            Toast.makeText(UpdateActivity.this, "请求权限被拒绝", Toast.LENGTH_LONG).show();
                            break;
                        }
                    }
                }else{
                    Toast.makeText(UpdateActivity.this, "已受权", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }
    //弹出提示框
    private void showDialog(){
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setMessage("录像须要相机、录音和读写权限，是否去设置？")
                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        goToAppSetting();
                    }
                })
                .setNegativeButton("否", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setCancelable(false)
                .show();
    }
    // 跳转到当前应用的设置界面
    private void goToAppSetting(){
        Intent intent = new Intent();
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        Uri uri = Uri.fromParts("package", getPackageName(), null);
        intent.setData(uri);
        startActivity(intent);
    }
}